package com.university.mentalhealthplatform.studentV3.service;

import com.university.mentalhealthplatform.appModels.Assessment;
import com.university.mentalhealthplatform.appModels.Student;
import com.university.mentalhealthplatform.exception.UserNotFoundException;
import com.university.mentalhealthplatform.global.rbac.model.User;
import com.university.mentalhealthplatform.global.rbac.service.entity.BaseUserService;
import com.university.mentalhealthplatform.studentV3.dto.AssessmentDTOV3;
import com.university.mentalhealthplatform.studentV3.dto.FilterParamsV3;
import com.university.mentalhealthplatform.studentV3.repository.AssessmentRepositoryV3;
import com.university.mentalhealthplatform.utils.stringUtils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class AssessmentServiceV3 {

    @Autowired
    private AssessmentRepositoryV3 assessmentRepositoryV3;// 注入 AssessmentRepository，用于保存评估结果
    @Autowired
    private BaseUserService userService; // 注入 UserService，用于获取用户信息
    private static final Logger logger = LoggerFactory.getLogger(AssessmentServiceV3.class);
    @Autowired
    private StudentServiceV3 studentService;


    public List<AssessmentDTOV3> getFilteredAssessments(FilterParamsV3 filterParamsV3) {
        // 对 filterParams 中的字符串字段进行 convertEmptyToNull 处理
        String college = StringUtils.convertEmptyToNull(filterParamsV3.getCollege());
        String major = StringUtils.convertEmptyToNull(filterParamsV3.getMajor());
        String gender = StringUtils.convertEmptyToNull(filterParamsV3.getGender());
        String grade = StringUtils.convertEmptyToNull(filterParamsV3.getGrade());

        // 打印处理后的筛选参数进行调试
        logger.info("Received filter params after conversion: College: {}, Major: {}, StartAge: {}, EndAge: {}, Gender: {}, Grade: {}",
                college,
                major,
                filterParamsV3.getStartAge(),
                filterParamsV3.getEndAge(),
                gender,
                grade);

        // 调用查询方法获取筛选结果
        List<Assessment> assessments = assessmentRepositoryV3.findByFilterParams(
                college,
                major,
                filterParamsV3.getStartAge(),
                filterParamsV3.getEndAge(),
                gender,
                grade
        );

        // Convert Assessment entities to AssessmentDTOs
        return assessments.stream()
                .map(assessment -> new AssessmentDTOV3(
                        assessment.getId(),
                        assessment.getScore(),
                        assessment.getEvaluation(),
                        assessment.getSubmittedTime(),
                        assessment.getStudent().getId()
                ))
                .collect(Collectors.toList());
    }
    private LocalDateTime convertToLocalDateTime(Date date) {
        return date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
    }




    public void saveAssessmentResult(AssessmentDTOV3 result, String currentUsername) {
        // 通过 UserService 获取当前用户信息
        User user = userService.findByUsername(currentUsername)
                .orElseThrow(() -> new UserNotFoundException("用户未找到：" + currentUsername));

        // 使用 user 获取ID并将其与评估结果关联
        // 这里可以将 user.id 作为实体的学生ID或其他逻辑
        assessmentRepositoryV3.save(convertToEntity(result, user.getId()));
    }

    private Assessment convertToEntity(AssessmentDTOV3 dto, UUID userId) {
        // 此方法将 AssessmentDTO 转换为 Assessment 实体
        Assessment assessment = new Assessment();
        assessment.setScore(dto.getScore());
        assessment.setEvaluation(dto.getEvaluation());

        // 获取 student 对象
        Optional<Student> student = studentService.findById(userId);
        System.out.println(student.isEmpty());

        // 检查 Optional 中是否包含值
        Student studentEntity = student.orElseThrow(() -> new UserNotFoundException("用户未找到：" + userId));

        assessment.setStudent(studentEntity);

        return assessment;
    }



}